import {
  vocabularyGrammarQuestions,
  dialogueAndClozeQuestions,
  readingQuestions,
  writingQuestions,
} from "./questions-data"

// 从环境变量获取API基础URL，如果未设置则使用默认值
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:3001/api"

// 通用的fetch函数，带有错误处理和超时
async function fetchWithTimeout(url: string, options: RequestInit = {}, timeout = 5000) {
  const controller = new AbortController()
  const id = setTimeout(() => controller.abort(), timeout)

  try {
    const response = await fetch(url, {
      ...options,
      signal: controller.signal,
    })

    clearTimeout(id)

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`)
    }

    return await response.json()
  } catch (error) {
    console.error(`Error fetching from ${url}:`, error)
    throw error
  }
}

// 获取词汇与语法题目
export async function getVocabularyGrammarQuestions() {
  try {
    const data = await fetchWithTimeout(`${API_BASE_URL}/questions/vocabulary-grammar`)
    return data
  } catch (error) {
    console.log("Falling back to local vocabulary grammar data")
    return vocabularyGrammarQuestions
  }
}

// 获取情景对话与完形填空题目
export async function getDialogueAndClozeQuestions() {
  try {
    const data = await fetchWithTimeout(`${API_BASE_URL}/questions/dialogue-cloze`)
    return data
  } catch (error) {
    console.log("Falling back to local dialogue and cloze data")
    return dialogueAndClozeQuestions
  }
}

// 获取阅读理解题目
export async function getReadingQuestions() {
  try {
    const data = await fetchWithTimeout(`${API_BASE_URL}/questions/reading`)
    return data
  } catch (error) {
    console.log("Falling back to local reading data")
    return readingQuestions
  }
}

// 获取写作题目
export async function getWritingQuestions() {
  try {
    const data = await fetchWithTimeout(`${API_BASE_URL}/questions/writing`)
    return data
  } catch (error) {
    console.log("Falling back to local writing data")
    return writingQuestions
  }
}

// 提交用户答案
export async function submitAnswer(questionType: string, questionId: number, userAnswer: string) {
  try {
    const response = await fetchWithTimeout(`${API_BASE_URL}/answers/submit`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        questionType,
        questionId,
        userAnswer,
        userId: localStorage.getItem("userId") || "anonymous",
        timestamp: new Date().toISOString(),
      }),
    })
    return response
  } catch (error) {
    console.error("Error submitting answer:", error)
    // 如果提交失败，我们仍然在本地存储答案
    return { success: false, error: "Failed to submit to server, saved locally" }
  }
}

// 获取用户错题
export async function getUserWrongAnswers(userId: string) {
  try {
    const data = await fetchWithTimeout(`${API_BASE_URL}/users/${userId}/wrong-answers`)
    return data
  } catch (error) {
    console.log("Falling back to local wrong answers data")
    // 从本地存储获取错题
    return JSON.parse(localStorage.getItem("wrongAnswers") || "[]")
  }
}

// 获取用户进度
export async function getUserProgress(userId: string) {
  try {
    const data = await fetchWithTimeout(`${API_BASE_URL}/users/${userId}/progress`)
    return data
  } catch (error) {
    console.log("Falling back to local progress data")
    // 从本地存储获取进度
    return JSON.parse(localStorage.getItem("progress") || "{}")
  }
}

// 保存用户进度
export async function saveUserProgress(userId: string, progress: any) {
  try {
    const response = await fetchWithTimeout(`${API_BASE_URL}/users/${userId}/progress`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(progress),
    })
    return response
  } catch (error) {
    console.error("Error saving progress:", error)
    // 如果保存失败，我们仍然在本地存储进度
    localStorage.setItem("progress", JSON.stringify(progress))
    return { success: false, error: "Failed to save to server, saved locally" }
  }
}

// 保存错题
export async function saveWrongAnswer(userId: string, wrongAnswer: any) {
  try {
    const response = await fetchWithTimeout(`${API_BASE_URL}/users/${userId}/wrong-answers`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(wrongAnswer),
    })
    return response
  } catch (error) {
    console.error("Error saving wrong answer:", error)
    // 如果保存失败，我们仍然在本地存储错题
    const storedWrongAnswers = JSON.parse(localStorage.getItem("wrongAnswers") || "[]")
    localStorage.setItem("wrongAnswers", JSON.stringify([...storedWrongAnswers, wrongAnswer]))
    return { success: false, error: "Failed to save to server, saved locally" }
  }
}

// 删除错题
export async function deleteWrongAnswer(userId: string, questionId: number) {
  try {
    const response = await fetchWithTimeout(`${API_BASE_URL}/users/${userId}/wrong-answers/${questionId}`, {
      method: "DELETE",
    })
    return response
  } catch (error) {
    console.error("Error deleting wrong answer:", error)
    // 如果删除失败，我们仍然在本地删除错题
    const storedWrongAnswers = JSON.parse(localStorage.getItem("wrongAnswers") || "[]")
    const updatedWrongAnswers = storedWrongAnswers.filter((item: any) => item.id !== questionId)
    localStorage.setItem("wrongAnswers", JSON.stringify(updatedWrongAnswers))
    return { success: false, error: "Failed to delete from server, deleted locally" }
  }
}

// 清空错题
export async function clearWrongAnswers(userId: string) {
  try {
    const response = await fetchWithTimeout(`${API_BASE_URL}/users/${userId}/wrong-answers/clear`, {
      method: "DELETE",
    })
    return response
  } catch (error) {
    console.error("Error clearing wrong answers:", error)
    // 如果清空失败，我们仍然在本地清空错题
    localStorage.setItem("wrongAnswers", JSON.stringify([]))
    return { success: false, error: "Failed to clear from server, cleared locally" }
  }
}
